import 'package:flutter/cupertino.dart';
import 'package:flutter/material.dart';
import 'package:flutter_learn_vi/src/bean/bean_category.dart';
import 'package:flutter_learn_vi/src/bean/bean_exam_test_count.dart';
import 'package:flutter_learn_vi/src/common/user_helper.dart';
import 'package:flutter_learn_vi/src/net/dio_utils.dart';
import 'package:flutter_learn_vi/src/page/common/common_dialog.dart';
import 'package:flutter_learn_vi/src/page/common/common_loading_dialog.dart';
import 'package:flutter_learn_vi/src/page/common/common_nodata_widget.dart';
import 'package:flutter_learn_vi/src/page/topic/topic_details_page.dart';
import 'package:flutter_learn_vi/src/page/topic/topic_enum.dart';
import 'package:flutter_learn_vi/src/utils/navigator_utils.dart';
import 'package:flutter_learn_vi/src/utils/toast_utils.dart';

import 'exam_rule_page.dart';
import 'exam_select_class_page.dart';

/// 创建人： Created by zhaolong
/// 创建时间：Created by  on 2021/1/18.
///
/// 可关注公众号：我的大前端生涯   获取最新技术分享
/// 可关注网易云课堂：https://study.163.com/instructor/1021406098.htm
/// 可关注博客：https://blog.csdn.net/zl18603543572
///
///
enum ExamPcType {
  common,
  v1,
}

/// 在线机考
class ExampPcItemPage extends StatefulWidget {
  final ExamPcType pageType;

  const ExampPcItemPage({Key key, this.pageType = ExamPcType.common})
      : super(key: key);

  @override
  _ExampPcItemPageState createState() => _ExampPcItemPageState();
}

class _ExampPcItemPageState extends State<ExampPcItemPage> {
  @override
  void initState() {
    super.initState();
    getCategorys();
  }

  int groupValuea = 0;

  @override
  Widget build(BuildContext context) {
    return buildContainer();
  }

  CategoryBean _cataBean;

  //选中的二级分类
  CategoryItemBean _temBean;

  String _selectCategoryText = "请选择";

  Widget buildContainer() {
    if (_isLoading) {
      return LoadingWidget();
    }
    if (_categoryList.length == 0) {
      return NoDataWidget(
        clickCallBack: () {
          getCategorys();
        },
      );
    }
    if (_examTestCountConfigBean.terminal == "pc") {
      return Center(child: Text("请在电脑端登录考试"));
    }
    return Container(
      width: double.infinity,
      padding: EdgeInsets.all(20),
      child: Column(
        children: [
          buildClassRow(),
          SizedBox(
            height: 30,
          ),
          buildRow(),
          SizedBox(
            height: 30,
          ),
          ElevatedButton(
            onPressed: () {
              if (groupValuea == 0) {
                ToastUtils.showToast("请选择考试模式");
                return;
              }
              startExamFunction();
            },
            child: Text("开始考试"),
          ),
          buildExpanded()
        ],
      ),
    );
  }

  Row buildClassRow() {
    return Row(
      children: [
        Text(
          "请选择分类",
          style: TextStyle(fontWeight: FontWeight.w500, fontSize: 16),
        ),
        Expanded(
          child: Container(
            margin: EdgeInsets.only(left: 10),
            padding: EdgeInsets.only(left: 8, right: 8, bottom: 4, top: 4),
            decoration: BoxDecoration(
                border: Border.all(),
                borderRadius: BorderRadius.all(Radius.circular(4))),
            child: InkWell(
              onTap: () {
                NavigatorUtils.pushPage(
                    context,
                    ExamSelectClassPage(
                      categoryList: _categoryList,
                    ), callback: (value) {
                  //点击反退里关闭页面也会回调 数据为 null
                  if (value != null) {
                    Map map = value;

                    //选中的一级分类
                    _cataBean = map["data"];
                    //选中的二级分类
                    _temBean = map["dataLevel"];
                    //设置数据显示
                    _selectCategoryText =
                        _cataBean.label + "-" + _temBean.label;
                    setState(() {});
                  }
                });
              },
              child: Row(
                children: [
                  Expanded(child: Text("$_selectCategoryText")),
                  Icon(
                    Icons.arrow_forward_ios,
                    size: 16,
                  )
                ],
              ),
            ),
          ),
        )
      ],
    );
  }

  Row buildRow() {
    return Row(
      crossAxisAlignment: CrossAxisAlignment.start,
      children: [
        Container(
          margin: EdgeInsets.only(top: 16),
          child: Text(
            "请选择模式",
            style: TextStyle(fontWeight: FontWeight.w500, fontSize: 16),
          ),
        ),
        Expanded(
          child: Column(
            mainAxisSize: MainAxisSize.min,
            children: [
              RadioListTile(
                value: 1,
                groupValue: this.groupValuea,
                title: Text('练习模式'),
                onChanged: (v) {
                  setState(() {
                    this.groupValuea = v;
                  });
                },
              ),
              RadioListTile(
                value: 2,
                groupValue: this.groupValuea,
                title: Text('考试模式'),
                onChanged: (v) {
                  setState(() {
                    this.groupValuea = v;
                  });
                },
              ),
            ],
          ),
        )
      ],
    );
  }

  Expanded buildExpanded() {
    return Expanded(
      child: Column(
        mainAxisAlignment: MainAxisAlignment.end,
        children: [
          TextButton(
            child: Text("考试规则"),
            onPressed: () {
              NavigatorUtils.pushPage(context, ExamRulePage());
            },
          ),
          SizedBox(
            height: 22,
          )
        ],
      ),
    );
  }

  bool _isLoading = true;
  List<CategoryBean> _categoryList = [];
  ExamTestCountConfigBean _examTestCountConfigBean;

  Future<bool> getCategorys() async {
    Map<String, dynamic> map = Map();
    //post请求发送
    ResponseInfo responseInfo = await DioUtils.instance.postRequest(
      url: HttpHelper.pcTestClass,
      jsonMap: map,
    );
    if (responseInfo.success) {
      List list = responseInfo.data;
      _categoryList = [];
      list.forEach((element) {
        CategoryBean newsBean = CategoryBean.fromJson(element);
        _categoryList.add(newsBean);
      });
    }
    ResponseInfo responseRoulesInfo = await DioUtils.instance.postRequest(
      url: HttpHelper.exampRuleUrl,
    );
    if (responseRoulesInfo.success) {
      _examTestCountConfigBean =
          ExamTestCountConfigBean.fromMap(responseRoulesInfo.data);
      UserHelper.getInstance.examTestCountConfigBean = _examTestCountConfigBean;
    }
    _isLoading = false;
    if (mounted) {
      setState(() {});
    }

    return Future.value(true);
  }

  void startExamFunction() {
    if (_cataBean == null) {
      ToastUtils.showToast("请选择考试分类");
      return;
    }
    String message = _temBean.label;
    if (_temBean != null) {
      message = "$message - ${_cataBean.label}";
    }
    showCommonAlertDialog(
        context: context,
        selectText: "确定",
        cancleText: "重新选择",
        contentMessag: "确定选择考试 ${message}",
        selectCallBack: () {
          examSelectQuestions();
        });
  }

  //开始抽题
  void examSelectQuestions() {
    NavigatorUtils.pushPage(
        context,
        TopicDetilsPage(
          pageTitle: "在线机考",
          topicEnum: TopicEnum.pcTest,
          examType: groupValuea == 1 ? "N" : "Y",
          categoryOne: _cataBean.value,
          categoryTwo: _temBean.value,
        ),
        isReplace: true);
  }
}
